﻿using Bangle.SerialPort;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp;

namespace Bangle.Abp.SerialPort.ConsoleTestApp
{
    public class ConsoleTestAppHostedService : IHostedService
    {
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using (var application = AbpApplicationFactory.Create<AbpSerialPortConsoleTestAppModule>())
            {
                application.Initialize();


                using (var scope = application.ServiceProvider.CreateAsyncScope())
                {
                    var sender = scope.ServiceProvider.GetService<ISerialPortSender>();

                    for (var i = 0; i < 1000; i++)
                    {
                        var bytes = System.Text.Encoding.ASCII.GetBytes($"WoshiDjiao:{i}");
                        await sender.SendAsync("Default", bytes);
                        await Task.Delay(1000);
                    }
                }

                application.Shutdown();
            }
        }

        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
    }
}
